<template>
  <el-card class="box-card" shadow="hover">
    <!-- 添加按钮 -->
    <template #header>
      <el-button type="primary" :icon="Plus" size="default" @click="AddChange">添加</el-button>
    </template>
    <!-- 表格 -->
    <el-table row-key="id" :data="data.detail" stripe border style="width: 100%" v-loading="loading">
      <!-- 序号列 -->
      <el-table-column align="center" type="index" label="序号" width="80" />
      <!-- 品牌名字列 -->
      <el-table-column prop="tmName" label="品牌名称" />
      <!-- 品牌logo列 -->
      <el-table-column prop="logoUrl" label="品牌LOGO">
        <template #default="scope">
          <img :src="scope.row.logoUrl" :alt="scope.row.tmName" style="width: 50px; height: 50px" />
        </template>
      </el-table-column>
      <!-- 修改删除列 -->
      <el-table-column label="操作">
        <template #default="scope">
          <el-tooltip class="box-item" effect="dark" content="修改" placement="top">
            <el-button size="default" :icon="Edit" type="warning" @click="EditChange(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip class="box-item" effect="dark" content="删除" placement="top">
            <el-button size="default" :icon="Delete" type="danger" @click="removeChange(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      v-model:currentPage="current"
      v-model:page-size="pages"
      :page-sizes="[3, 6, 9]"
      :small="small"
      layout="  prev, pager, next, jumper,->,sizes,total,"
      :total="total"
      @size-change="(val) => getData(1, val)"
      @current-change="(val) => getData(val, pages)"
      style="margin-top: 20px"
    />

    <!-- 弹出的对话框 -->
    <el-dialog v-model="dialogFormVisible" draggable :title="`${trademark.id ? '修改数据' : '新增数据'}`">
      <el-form :model="trademark" style="width: 80%" label-width="100px" ref="FormRef" :rules="rules">
        <!--品牌名称  -->
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="trademark.tmName" autocomplete="off" />
        </el-form-item>
        <!-- 上传图片 -->
        <el-form-item label="图片" prop="logoUrl">
          <!-- 上传图片的组件库 -->
          <el-upload class="avatar-uploader" :action="`${BaseUrl}//admin/product/fileUpload`" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <!-- 上传图片时候的效果 -->
            <el-icon v-if="uploadLoading" class="avatar-uploader-icon"><Loading /></el-icon>
            <!-- 上传的图片显示 -->
            <img v-else-if="trademark.logoUrl" :src="trademark.logoUrl" class="avatar" />
            <!-- 显示上传的时候的加号 -->
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="addOrupdate">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>
<script lang="ts">
export default {
  name: "Trademark",
};
</script>
<script lang="ts" setup>
import { Plus, Edit, Delete, Loading } from "@element-plus/icons-vue";
import { ref, onMounted, reactive, nextTick } from "vue";
import { reqGetTrademarkListAll, reqGetTrademarkList, reqAddOrUpdateTrademark, reqDeleteTrademarkById } from "@/api/product/trademark";
import type { TrademarkListModel, TrademarkModel, TrademarkPageListModel } from "@/api/product/model/trademarkModel";
import { ElMessage, ElMessageBox } from "element-plus";
// 引入表单验证需要的类型
import type { FormInstance, FormRules } from "element-plus";
// 定义长传图片需要的类型
import type { UploadProps } from "element-plus";
const small = ref(false);
const current = ref(1);
const pages = ref(3);
const total = ref(0);
const loading = ref(false);
// 定义dom对象
const FormRef = ref<FormInstance>();
// 定义接受数据的容器
const data = reactive<{ detail: TrademarkListModel }>({
  detail: [] as TrademarkListModel,
});
// 定义对话框的显示
const dialogFormVisible = ref(false);

// 定于trademark数据
const trademark = reactive<TrademarkModel>({
  tmName: "",
  logoUrl: "",
});

// 修改的回调
const EditChange = (row: TrademarkModel) => {
  Object.assign(trademark, row);
  dialogFormVisible.value = true;
};
// 删除的回调
const removeChange = (row: TrademarkModel) => {
  ElMessageBox.confirm(`您确定要删除这个${row.tmName}的数据吗`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "不确定",
    type: "warning",
  })
    .then(async () => {
      await reqDeleteTrademarkById(row.id as number);
      getData();
      ElMessage.success("删除成功");
    })
    .catch(() => {
      ElMessage.error("删除失败了");
    });
};

const AddChange = () => {
  trademark.id = undefined;
  trademark.logoUrl = "";
  trademark.tmName = "";
  dialogFormVisible.value = true;
  nextTick(() => {
    FormRef.value?.resetFields();
  });
};

// 定义获取列表的数据
const getData = async (page: number = current.value, limit: number = pages.value) => {
  loading.value = true;
  let res = await reqGetTrademarkList(page, limit);
  data.detail = res.records;
  total.value = res.total;
  current.value = page;
  pages.value = limit;
  loading.value = false;
  ElMessage.success("获取列表成功了");
};
// 挂载完之后获取数据
onMounted(() => {
  getData();
});
// 点击切换页码的回调
// const handlerPageChange = async (page: number) => {
//   data.detail = (await reqGetTrademarkList(current.value, page)).records;
// };
// 点击切换多少页一条的回调
// const handlerSizeChange = async (page: number) => {
//   data.detail = (await reqGetTrademarkList(page, pages.value)).records;
// };

// 定义基础的路径
const BaseUrl = import.meta.env.VITE_API_URL;

// 定义成功与失败的回调
const handleAvatarSuccess: UploadProps["onSuccess"] = (res, file) => {
  // 吧图片的地址赋值给trademark
  trademark.logoUrl = res.data;
  // 取消加载效果
  uploadLoading.value = false;
  // 表单的验证
  FormRef.value?.validateField("logoUrl");
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (file) => {
  const isJpgOrPng = ["image/jpeg", "image/png"].includes(file.type);
  if (!isJpgOrPng) {
    ElMessage.error("上传的图片格式不对");
    return false;
  }
  const isLt50k = file.size / 1024 > 50;
  if (isLt50k) {
    ElMessage.error("图片过大,请换一张");
    return false;
  }
  uploadLoading.value = true;
  return true;
};
// 定义上传的时候的加载效果
const uploadLoading = ref<boolean>(false);
// 定义自定义规则（名字）
const validateTmName = (rule: any, value: any, callback: any) => {
  if (value.length < 2 || value.length > 10) {
    callback("品牌的名字必须在2到10个字之内");
  } else {
    callback();
  }
};
// 定义规则
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: "必须写你的品牌名字" },
    { validator: validateTmName, trigger: "blur" },
  ],
  logoUrl: [
    {
      required: true,
      message: "必须上传一个图片",
    },
  ],
});

// 定义弹框的确认按钮的验证
const addOrupdate = () => {
  FormRef.value?.validate(async (valid, fields) => {
    if (!valid) {
      return;
    }
    // 到这里就说明你通过了
    try {
      await reqAddOrUpdateTrademark(trademark);
      dialogFormVisible.value = false;
      ElMessage.success("操作成功");
      getData(1, 3);
    } catch (error) {
      alert("出错了");
    }
  });
};
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
